package com.dagene.weixin.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.ss.usermodel.Workbook;

public class ExcelUtil {

	private InputStream inputStream;

	public String exportExcel(HttpServletRequest request,
			Map<String, Object> para, String model) {
		try {
			// ------------------------开始报表
			XLSTransformer transformer = new XLSTransformer();
			Workbook wb;
			try {
				// 模板路径
				String classPath = this.getClass().getClassLoader()
						.getResource(model).getPath();
				// 真实导出路径
				String filepath = File.separator + "file" + File.separator
						+ "document";
				String url = request.getSession().getServletContext()
						.getRealPath(filepath);

				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

				String classPath2 = url + File.separator + "report"
						+ sdf.format(new Date()) + ".xlsx";
				File file = new File(classPath2);
				file.createNewFile();
				transformer.transformXLS(classPath, para, classPath2); // 在classPath2下生成excel文件
				inputStream = new FileInputStream(new File(classPath2));
				wb = transformer.transformXLS(new FileInputStream(classPath),
						para); // 获得Workbook对象

				wb.write(new FileOutputStream(classPath2)); // 导出Excel
				// System.out.println(classPath2);
				String ss = File.separator + "file"
						+ classPath2.split("file")[1];
				System.out.println(ss);
				inputStream.close();
				return ss;
			} catch (Exception e) {
				throw new Exception(e);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "failed";
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
}